package com.hisan.freeride.home.activity;

import android.app.Activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.blankj.utilcode.util.LogUtils;
import com.hisan.freeride.R;
import com.hisan.freeride.common.Dialog.PushDialogLogok;
import com.hisan.freeride.common.alertwindow.BasePopupWindow;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseActivity;
import com.hisan.freeride.common.base.BaseAppLication;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.event.DataSynEvent;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.ListUtils;
import com.hisan.freeride.common.view.CustomButton;
import com.hisan.freeride.common.view.FlowLayout;
import com.hisan.freeride.common.view.ListPopup;
import com.hisan.freeride.databinding.PushBinding;
import com.hisan.freeride.home.model.Tag;
import com.kejiang.yuandl.mytimepick.timepick.MyTimePicker;
import com.lzy.okgo.OkGo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 创建时间 : 2017/6/15
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：发布行程页面
 */
public class PushActivity extends BaseActivity<PushBinding> {
    private List<Tag> strings;
    //行程备注(名称,id)
    private List<String>names=new LinkedList<>();
    private List<String>ids=new ArrayList<>();
    //最大乘坐人数（默认为11）
    private  int Limit=7;
    private Intent intent;
    //人数选择弹窗
    private ListPopup mListPopup;
    private ListPopup.Builder builder;
    private List<Integer> integers=new ArrayList<>();
    //行程备注弹窗
    private PushPopup pushPopup;


    @Override
    protected int getLayoutId() {
        return R.layout.push;
    }

    @Override
    protected void initView() {
        builder=new ListPopup.Builder(this);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initEvent() {
        for (int i=1;i<=Limit;i++){
            builder.addItem(i+"人");
            integers.add(i);
            mListPopup=builder.build();
        }
        mBinding.topBack.setOnClickListener(v -> finishActivity(true));
        mBinding.label.setOnClickListener(v -> {
            if (!CollectionUtils.isNullOrEmpty(strings)){
                pushPopup.showPopupWindow();
            }else{
                showToast("暂无标签参数");}
        });
        mBinding.total.setOnClickListener(v -> {
            mListPopup.showPopupWindow();
            mListPopup.setOnListPopupItemClickListener(position -> {
                if (!CollectionUtils.isNullOrEmpty(integers)) {
                    mBinding.totalName.setText(integers.get(position)+"人");
                }
                if (!CollectionUtils.isNullOrEmpty(mListPopup))mListPopup.dismiss();
            });
        });
        mBinding.selectTime.setOnClickListener(v -> showChoseTimeDialog());
        mBinding.push.setOnClickListener(v -> {
            String tag_id="";
            String total="";
            int remaining=0;
            //城市id
            int cityid= BaseAppLication.getInstance().getCityid();
            if (!CollectionUtils.isNullOrEmpty(ids)){
                tag_id= ListUtils.formatStr(ids);
            }
            //起点城市名
            String city= mBinding.address.getText().toString();
            //目的地城市名
            String  destination=mBinding.addressText.getText().toString();

            //乘坐人数
            String  totalname=mBinding.totalName.getText().toString();
            if (!CollectionUtils.isNullOrEmpty(totalname)){
                //乘坐的人的数量
                total=compile(totalname);
                //剩余座位
                remaining=Limit -convertToInt(total,1);
            }
            String year=mBinding.year.getText().toString();
            String phone= mBinding.phone.getText().toString();
            String way= mBinding.wayText.getText().toString();
            if(CollectionUtils.isNullOrEmpty(cityid)||CollectionUtils.isNullOrEmpty(tag_id)||
                    CollectionUtils.isNullOrEmpty(city)||CollectionUtils.isNullOrEmpty(destination)||
                    CollectionUtils.isNullOrEmpty(total)||  CollectionUtils.isNullOrEmpty(remaining)||
                    CollectionUtils.isNullOrEmpty(year)||
                    CollectionUtils.isNullOrEmpty(phone)){
                showToast("请输入完整信息.....");
                return;
            }
            year=year+":00";
            LogUtils.v("xxx",year);
            //城市ID,行程标签,始发地,目的地,始发地经度，维度，目地的经度，维度,乘坐人数,剩余座位,发车时间，access_token，电话
            Createtrip(cityid,tag_id,city,destination
                    ,total,remaining,year,phone,way);
        });

    }

    @Override
    protected void loadData(boolean isRefresh) {
        OkGo.<List<Tag>>get(AppConfig.Gettag)
                .tag(this)
                .execute(new DialogCallback<List<Tag>>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<List<Tag>> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            strings=new ArrayList<>();
                            if (!CollectionUtils.isNullOrEmpty(response.body())){
                                strings=response.body();
                                strings.add(0,new Tag(0,"免费免责"));
                                pushPopup=new PushPopup(PushActivity.this,strings);
                            }
                        }
                    }
                });
    }




    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(DataSynEvent event) {
        if (event.getid()==1){
            finishActivity(true);
        }
    }

    //发布行程
    //城市ID,行程标签,始发地,目的地,始发地经度，维度，目前的经度，维度,乘坐人数,剩余座位,发车时间，access_token，电话
    private  void Createtrip(int  city_id, String tag_id, String initially, String destination,
                           String people, int surplus, String departure_time
            , String mobile,String way){
        OkGo.post(AppConfig.Createtrip)
                .tag(this)
                .params("city_id",city_id)
                .params("tag_id",tag_id)
                .params("initially",initially)
                .params("destination",destination)
                .params("people",people)
                .params("surplus",surplus)
                .params("departure_time",departure_time)
                .params("mobile",mobile)
                .params("way",way)
                .execute(new DialogCallback<Object>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (isOk(response)){
                            if (CollectionUtils.isNullOrEmpty(intent))intent=new Intent();
                            setResult(2,intent);
                            PushDialogLogok.getInstance().show(getSupportFragmentManager(), "DialogLogok");
                        }else {
                            showError(response);
                        }

                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });
    }


    //截取字符串中数字
    public String compile(String msg){
        String mmsg="";
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(msg);
        mmsg=m.replaceAll("").trim();
        return mmsg;
    }


    //把String转化为int
    public static int convertToInt(String number, int defaultValue) {
        if (CollectionUtils.isNullOrEmpty(number)) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(number);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==99){
            if (!CollectionUtils.isNullOrEmpty(data)){
                String  site=data.getStringExtra("site");
                String  city=data.getStringExtra("city");
                mBinding.address.setText(city+ " · "+site);
            }
        }else if(resultCode==98){
            if (!CollectionUtils.isNullOrEmpty(data)){
                String  site=data.getStringExtra("site");
                String  city=data.getStringExtra("city");
                mBinding.addressText.setText(city+ " · "+site);
            }
        }
    }

    //行程备注弹窗
    class PushPopup extends BasePopupWindow {
        private View popupView;
        public PushPopup(Activity context, List<Tag>datas) {
            super(context);
            bindEvent(context,datas);
        }
        @Override
        public Animation getExitAnimation() {
            return null;
        }
        @Override
        protected View getClickToDismissView() {
            return popupView.findViewById(R.id.click_to_dismiss);
        }

        @Override
        public View getPopupView() {
            popupView= LayoutInflater.from(mContext).inflate(R.layout.push_remarks,null);
            return popupView;
        }

        @Override
        public View getAnimaView() {
            return popupView.findViewById(R.id.popup_anima);
        }

        private void bindEvent(Activity context, List<Tag> datas) {
            if (popupView!=null){
                FlowLayout flowLayout = (FlowLayout) popupView.findViewById(R.id.flowlayout);
                LinearLayout  cancel= (LinearLayout) popupView.findViewById(R.id.cancel);
                RelativeLayout  popup_view_cont= (RelativeLayout) popupView.findViewById(R.id.popup_view_cont);
                //添加数据
                flowLayout.addTags(context,datas);
                //设置是否单选
                flowLayout.setRadio(false);
                flowLayout.setTagOnClickListener((index, str, id, isChecked) -> {
                    if (!CollectionUtils.isNullOrEmpty(str)&&!CollectionUtils.isNullOrEmpty(id)){
                        int count = Collections.frequency(names,str);
                        if (count==0) {
                            names.add(str);
                        }
                        ids.add(id);
                        if (!isChecked){
                            deleteid(names,str);
                            deleteid(ids,id);
                        }
                    }
                });
                CustomButton push= (CustomButton) popupView.findViewById(R.id.push);
                push.setOnClickListener(v -> {
                    mBinding.labelName.removeAllViews();
                    if (!CollectionUtils.isNullOrEmpty(pushPopup))
                        pushPopup.dismiss();
                    if (!CollectionUtils.isNullOrEmpty(names)){
                        mBinding.labelbz.setBackgroundResource(R.drawable.textview_style2);
                        mBinding.labelbz.setText("免费免责");
                        mBinding.labelbz.setTextSize(11);
                        mBinding.labelbz.setTextColor(getResources().getColor(R.color.white));
                        for (int i = 0; i < names.size(); i++) {
                            View  view = LayoutInflater.from(PushActivity.this).inflate(R.layout.textview_item,null);
                            TextView tv = (TextView) view.findViewById(R.id.textView1);
                            tv.setTextColor(getResources().getColor(R.color.sdarkgray));
                            tv.setBackgroundResource(R.drawable.textview_style);
                            tv.setText(names.get(i));
                            mBinding.labelName.addView(view);
                        }
                    }
                });
                cancel.setOnClickListener(v -> {
                    if (!CollectionUtils.isNullOrEmpty(pushPopup))
                        pushPopup.dismiss();
                });
                popup_view_cont.setOnClickListener(v -> {
                    if (!CollectionUtils.isNullOrEmpty(pushPopup))
                        pushPopup. dismiss();
                });

            }
        }
    }



    //删除list中指定元素
    private void deleteid(List list, String gid){
        Iterator<String> sListIterator = list.iterator();
        while(sListIterator.hasNext()){
            String e = sListIterator.next();
            if(e.equals(gid)){
                sListIterator.remove();
            }
        }
    }
    private void showChoseTimeDialog() {
        final ArrayList<String> minutes = get64minutes();
        final ArrayList<String> hours = get24hours();
        final ArrayList<String> dates = get7Date();
        MyTimePicker myTimePicker = new MyTimePicker(this, dates, hours, minutes);
        myTimePicker.setSelectedItem(0, 0, 0);
        myTimePicker.setTitleText("选择时间");
        myTimePicker.setTitleTextSize(16);
        myTimePicker.setTopBackgroundColor(Color.parseColor("#FFEAEAEB"));
        myTimePicker.setTextSize(14);
        myTimePicker.setCancelText("取消");
        myTimePicker.setSubmitText("完成");
        myTimePicker.setSubmitTextColor(Color.parseColor("#F77B55"));
        myTimePicker.setLineColor(Color.parseColor("#FFEAEAEB"));
        myTimePicker.setTextColor(Color.parseColor("#000000"));
        myTimePicker.show();
        myTimePicker.setOnAddressPickListener((month, monday, miniutis) -> {
            Calendar c = Calendar.getInstance();
            //当前年份、月份
            int year = c.get(Calendar.YEAR);
            String data=compile(month);
            String mymonth=data.substring(0,2);
            String date=data.substring(2,4);
            mBinding.year.setText(year+"-"+mymonth+"-"+date+" "+compile(monday)+":"+compile(miniutis));
        });
    }
    /**
     * 获取从今天后的7天
     *
     * @return
     */
    private ArrayList<String> get7Date() {
        ArrayList<String> dates = new ArrayList<String>();
        for (int i = 0; i < 7; i++) {
            dates.add(getStatetime(i));
        }
        return dates;
    }

    /**
     * 获取24小时
     *
     * @return
     */
    private ArrayList<String> get24hours() {
        ArrayList<String> dates = new ArrayList<String>();
        for (int i = 0; i < 24; i++) {
            dates.add((i < 10 ? "0" + i : i) + "时");
        }
        return dates;
    }

    /**
     * 获取60分
     *
     * @return
     */
    private ArrayList<String> get64minutes() {
        int curentMiniutis = 0;
        ArrayList<String> dates = new ArrayList<String>();
        while(curentMiniutis<60){
            dates.add((curentMiniutis<10?("0"+curentMiniutis):curentMiniutis)+"分");
            curentMiniutis+=1;
        }
        return dates;
    }

    private String getStatetime(int i) {
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, i);
        Date monday = c.getTime();
        String preMonday = sdf.format(monday);
        return preMonday;
    }
}
